/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.service.plugin;

import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.client.LogClient;
import com.apache.client.UctCoreClient;
import com.apache.client.UctProtoclClient;
import com.apache.license.validator.TeaUtil;
import com.apache.passport.common.DesUtils;
import com.apache.passport.common.PassportHelper;
import com.apache.passport.entity.Token;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.SendService;
import com.apache.portal.common.annotion.AnntationBean;
import com.apache.portal.common.annotion.BeanFactory;
import com.apache.portal.common.enums.UserMethodEnum;
import com.apache.portal.common.oscache.BaseOsCache;
import com.apache.portal.common.oscache.OsCacheOtherManager;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.RequestTools;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.Role;
import com.apache.uct.common.entity.User;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * description:  uct3.0对接插件
 *
 * @author Hou Dayu 创建时间：2016-9-17
 */
@AnntationBean(name = "uct")
public class Uct3SystemPluginImpl implements PortalPlugin {

    private Logger log = LoggerFactory.getLogger(Uct3SystemPluginImpl.class);

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     */
    public Object doInvoke(HttpServletRequest request, HttpServletResponse response,
            Map<String, String> params) {
        String doCode = request.getParameter("doCode");
        if (StrUtil.isNull(doCode)) {
            doCode = params.get("doCode");
        }
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        ResultMsg msg = null;
        switch (UserMethodEnum.getName(doCode)) {
        case loginNoCode:
        case login:
            msg = login(request, response, params);
            break;
        case regUser:
        case regUserMailCode:
            msg = regUser(request, response, params);
            break;
        case editUser:
            msg = editUser(request, response, params);
            break;
        case FindPwd:
            msg = findPwd(request, response, params);
            break;
        case editPwd:
            msg = editUserPwd(request, response, params);
            break;
        case loginUser:
            getLoginUser(request);
            break;
        case userInfo://获取用户信息
            return getUserInfo(request, params);
        case isExist://判断用户是否存在
            return isExist(request, params);
        case logout:
            msg = logout(request, response, params);
            break;
        case userList:
            paramsMap.putAll(params);
            return UctCoreClient.searchUserByReflect(paramsMap);
        case logModelList:
            paramsMap.putAll(params);
            return LoadRpcService.service()
                    .doServiceClient("auditService", "logModelList", paramsMap,
                            PortalPubFactory.getInstance().getRpcInfo("audit"));
        case logOperationList:
            paramsMap.putAll(params);
            return LoadRpcService.service()
                    .doServiceClient("auditService", "logOperationList", paramsMap,
                            PortalPubFactory.getInstance().getRpcInfo("audit"));
        case viewLogDetail:
            paramsMap.putAll(params);
            return LoadRpcService.service()
                    .doServiceClient("auditService", "viewLogDetail", paramsMap,
                            PortalPubFactory.getInstance().getRpcInfo("audit"));
        case deptInfo:
            paramsMap.putAll(params);
            return LoadRpcService.service().doServiceClient("uctService", "deptEntity", paramsMap,
                    PortalPubFactory.getInstance().getRpcInfo("uct"));
        case logExecute://(saveModel/delModel/saveModelDetail/delModelDetail)
            paramsMap.putAll(params);
            String methodKey = "logExecute";
            if ("modelDetailList".equalsIgnoreCase(params.get("exeType"))) {
                methodKey = "logModelDetailList";
            }
            return LoadRpcService.service().doServiceClient("auditService", methodKey, paramsMap,
                    PortalPubFactory.getInstance().getRpcInfo("audit"));
        case configCopy:
            paramsMap.putAll(params);
            return LoadRpcService.service().doServiceClient("rpcService", "configAction", paramsMap,
                    PortalPubFactory.getInstance().getRpcInfo("rpc"));
        default:
            return userAdmin(params, request);
        }

        return msg;
    }

    @SuppressWarnings("unchecked")
    private Object userAdmin(Map params, HttpServletRequest request) {
        String doCode = String.valueOf(request.getAttribute("PathAttr0"));
        doCode = StrUtil.doNull(doCode, request.getParameter("doCode"));
        Object obj = null;
        ResultEntity entity = null;
        LoginUser loginUser = PortalPubFactory.getInstance().getLoginUser(request);
        if ("saveUser".equalsIgnoreCase(doCode)) {
            ResultMsg msg = new ResultMsg("F", "操作失败");
            params.put("method", "save");
            entity = UctProtoclClient.getInstance().doService("uctService", "userAction", params);
            if ("true".equalsIgnoreCase(String.valueOf(entity.getEntity())) || "T"
                    .equalsIgnoreCase(String.valueOf(entity.getEntity()))) {
                msg = new ResultMsg("T", entity.getMessage());
            } else {
                msg.setMsg(entity.getMessage());
            }
            return msg;
        } else if ("delUser".equalsIgnoreCase(doCode)) {
            ResultMsg msg = new ResultMsg("F", "操作失败");
            params.put("method", "delete");
            entity = UctProtoclClient.getInstance().doService("uctService", "userAction", params);
            if ("T".equalsIgnoreCase(String.valueOf(entity.getEntity()))) {
                msg = new ResultMsg("T", "操作成功");
            } else {
                msg.setMsg(entity.getMessage());
            }
            return msg;
        } else if ("userRoleData".equalsIgnoreCase(doCode)) {//拥有的角色
            //params.put("userId", loginUser.getUserId());
            params.put("userOrgId", loginUser.getOrgId());
            params.put("sysFlag", loginUser.getSysFlag());
            params.put("method", "userRoleData");
            entity = UctProtoclClient.getInstance()
                    .doService("uctService", "userActsAction", params);
            Map map = (Map) entity.getEntity();
            if ("0".equals(loginUser.getSysFlag()) && (null == map || "0"
                    .equals(String.valueOf(map.get("total"))))) {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("userEname", loginUser.getUserEname());
                ResultEntity entity2 = UctCoreClient.searchRoleByReflect(param);
                List<Role> roles = null;
                Map mapo = new HashMap();
                if ("true".equals(entity2.getResult()) && !ToolsUtil.isEmpty(entity2.getEntity())) {
                    request.getSession().setAttribute("loginUserRoles", entity2.getEntity());
                    roles = (List<Role>) entity2.getEntity();
                    mapo.put("total", roles.size());
                    mapo.put("rows", roles);
                }
                return mapo;
            }
            return map;
        } else if ("roleToUser".equalsIgnoreCase(doCode)) {//分配角色给用户(roleId,userId,flag,roleEname)
            params.put("method", "roleToUser");
            params.put("sysFlag", loginUser.getSysFlag());
            entity = UctProtoclClient.getInstance()
                    .doService("uctService", "userActsAction", params);
            ResultMsg msg = new ResultMsg("F", "操作失败");
            if ("true".equalsIgnoreCase(String.valueOf(entity.getEntity()))) {
                msg = new ResultMsg("T", "操作成功");
            } else {
                msg.setMsg(entity.getMessage());
            }
            return msg;
        } else if ("userRightRoleData".equalsIgnoreCase(doCode)) {//继承自角色的权限(userId,rows,page)
            params.put("method", "userRightRoleData");
            entity = UctProtoclClient.getInstance()
                    .doService("uctService", "userActsAction", params);
            obj = entity.getEntity();
        } else if ("userRightOrgData"
                .equalsIgnoreCase(doCode)) {//数据权限机构(id,userId,userOrgId,sysFlag)
            params.put("method", "userRightOrgData");
            params.put("userOrgId", loginUser.getOrgId());
            params.put("nowOrgIds", loginUser.getDataOrgIds());
            params.put("sysFlag", loginUser.getSysFlag());
            params.put("ParamType", "json");
            entity = UctProtoclClient.getInstance()
                    .doService("uctService", "userActsAction", params);
            obj = entity.getEntity();
        } else if ("userDataGive".equalsIgnoreCase(doCode)) {//分配数据权限给用户(objId,userId,giveType,flag)
            params.put("method", "userDataGive");
            ResultMsg msg = new ResultMsg("F", "操作失败");
            entity = UctProtoclClient.getInstance()
                    .doService("uctService", "userActsAction", params);
            if ("true".equalsIgnoreCase(String.valueOf(entity.getEntity()))) {
                msg = new ResultMsg("T", "操作成功");
            } else {
                msg.setMsg(entity.getMessage());
            }
            return msg;
        } else if ("authorizeAct".equalsIgnoreCase(doCode)) {//执行权限值分配(objId,id,actGiveType,flag)
            params.put("method", "authorizeAct");
            ResultMsg msg = new ResultMsg("F", "操作失败");
            entity = UctProtoclClient.getInstance()
                    .doService("uctService", "userActsAction", params);
            if ("true".equalsIgnoreCase(String.valueOf(entity.getEntity()))) {
                msg = new ResultMsg("T", "操作成功");
                String objType = String.valueOf(params.get("objType"));
                String iusId = String.valueOf(params.get("iusId"));
                if (StrUtil.isNotNull(objType) && StrUtil.isNotNull(iusId)) {
                    String cacheKey = "act_ius_" + iusId;
                    BaseOsCache oscache = OsCacheOtherManager.getInstance()
                            .getBaseOsCache("ius_port", 600);//
                    oscache.remove(cacheKey);
                }
            } else {
                msg.setMsg(entity.getMessage());
            }
            return msg;
        } else if ("userRightDeptData".equalsIgnoreCase(doCode)) {//数据权限部门(id,userId)
            params.put("method", "userRightDeptData");
            params.put("nowDeptIds", loginUser.getDataDeptIds());
            params.put("sysFlag", loginUser.getSysFlag());
            params.put("ParamType", "json");
            entity = UctProtoclClient.getInstance()
                    .doService("uctService", "userActsAction", params);
            obj = entity.getEntity();
        } else if ("roleActData"
                .equals(doCode)) {//获取(角色)权限分配列表id(FatherId),nowOrgId,nowSysUser,roleId,
            params.put("nowOrgId", loginUser.getOrgId());
            params.put("nowSysUser", loginUser.getSysFlag());
            params.put("method", "roleActData");
            params.put("ParamType", "json");
            entity = UctProtoclClient.getInstance().doService("uctService", "roleAction", params);
            obj = entity.getEntity();
        } else if ("saveAct".equalsIgnoreCase(doCode)) {//createUser,reqIp
            ResultMsg msg = new ResultMsg("F", "操作失败");
            params.put("method", "save");
            params.put("createUser", loginUser.getUserEname());
            params.put("reqIp", PortalPubFactory.getLocalIp());
            entity = UctProtoclClient.getInstance().doService("uctService", "actAction", params);
            if ("true".equalsIgnoreCase(String.valueOf(entity.getEntity())) || "T"
                    .equalsIgnoreCase(String.valueOf(entity.getEntity()))) {
                msg = new ResultMsg("T", "操作成功");
            } else {
                msg.setMsg(entity.getMessage());
            }
            return msg;
        } else if ("delAct".equalsIgnoreCase(doCode)) {//createUser,reqIp,id
            ResultMsg msg = new ResultMsg("F", "操作失败");
            params.put("method", "delete");
            params.put("createUser", loginUser.getUserEname());
            params.put("reqIp", PortalPubFactory.getLocalIp());
            entity = UctProtoclClient.getInstance().doService("uctService", "actAction", params);
            if ("true".equalsIgnoreCase(String.valueOf(entity.getEntity())) || "T"
                    .equalsIgnoreCase(String.valueOf(entity.getEntity()))) {
                msg = new ResultMsg("T", "操作成功");
            } else {
                msg.setMsg(entity.getMessage());
            }
            return msg;
        } else if ("treeAct".equalsIgnoreCase(doCode)) {//id,sysEname,actId
            params.put("method", "tree");
            params.put("ParamType", "json");
            entity = UctProtoclClient.getInstance().doService("uctService", "actAction", params);
            obj = entity.getEntity();
        } else if ("actInfo".equalsIgnoreCase(doCode)) {//id,sysEname,actId
            params.put("method", "byId");
            entity = UctProtoclClient.getInstance().doService("uctService", "actAction", params);
            return entity;
        } else if ("userRightAct".equalsIgnoreCase(doCode)) {
            params.put("method", "userRightAct");
            params.put("ParamType", "json");
            if (!"1".equalsIgnoreCase(loginUser.getSysFlag())) {
                params.put("nowDeptId", loginUser.getDeptId());
                params.put("userOrgId", loginUser.getOrgId());
            }
            params.put("sysFlag", loginUser.getSysFlag());
            entity = UctProtoclClient.getInstance()
                    .doService("uctService", "userActsAction", params);
            obj = entity.getEntity();
        } else if ("userRightAll".equalsIgnoreCase(doCode)) {
            params.put("method", "userRightAll");
            entity = UctProtoclClient.getInstance()
                    .doService("uctService", "userActsAction", params);
            obj = entity.getEntity();
        }
        return obj;
    }

    private Object getUserInfo(HttpServletRequest request, Map<String, String> params) {
        String username = StrUtil.doNull(params.get("userEname"), "");
        String userId = StrUtil.doNull(params.get("userId"), "");

        ResultEntity entity = null;
        if (StrUtil.isNull(userId)) {
            entity = UctCoreClient.getUserByProperty("userEname", username);
        } else {
            entity = UctCoreClient.getUserByProperty("userId", userId);
        }
        if (("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
            return entity.getEntity();
        }
        return null;
    }

    /**
     * description:  获取当前登录用户信息
     */
    private void getLoginUser(HttpServletRequest request) {
        if (null == request.getSession().getAttribute("loginUser")) {
            String cookieValue = PassportHelper.getInstance().getCurrCookie(request);
            if (StrUtil.isNull(cookieValue)) {
                request.getSession().removeAttribute("loginUser");
            } else {
                try {
                    String value = PassportHelper.getInstance().getCurrCookie(request, "_uc.sso");
                    if (StrUtil.isNotNull(value)) {
                        value = DesUtils.getInstance().decrypt(value);
                        LoginUser loginUser = PBOSSOTools
                                .getLoginUserFromUserCenter(value, cookieValue);
                        if (null != loginUser)
                            request.getSession().setAttribute("loginUser", loginUser);
                    }
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     * description:  用户登录方法
     */
    private ResultMsg login(HttpServletRequest request, HttpServletResponse response,
            Map<String, String> params) {
        ResultMsg msg = new ResultMsg("F", "登录失败");
        Map<String, Object> maps = new HashMap<String, Object>();
        if (StrUtil.isNull(params.get("username")) || StrUtil.isNull(params.get("password"))) {
            msg = new ResultMsg("F", "用户名或密码不能为空");
            return msg;
        }
        String sysEname = ToolsUtil.getInstance().getValueByKey("sysEname");
        maps.put("userEname", params.get("username"));
        maps.put("Client-IP", StrUtil.doNull(params.get("Client-IP"), RequestTools.getIp(request)));
        //		try {
        //			maps.put("userPass", MD5Utils.crypt(params.get("password")));
        //		} catch (NoSuchAlgorithmException e) {
        //		}
        maps.put("userPass", params.get("password"));
        maps.put("sysEname", sysEname);
        maps.put("addressIP", maps.get("Client-IP"));
        ResultEntity entity = LoadRpcService.service()
                .doServiceClient("ssoService", "outSideSocketLoginService", maps,
                        PortalPubFactory.getInstance().getRpcInfo("sso"));
        if (("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
            if (entity.getEntity() instanceof String) {
                String userMsg = String.valueOf(entity.getMessage());
                log.error("portal登录提示：" + userMsg);

                if (userMsg.indexOf("用户已停用") > -1) {
                    msg = new ResultMsg("F", "您的账户正在审核，请耐心等待！");
                } else if (userMsg.indexOf("删除") > -1) {
                    msg = new ResultMsg("F", "您的账户已关闭登录操作，请联系管理人员！");
                } else {
                    if ("密码错误".equals(userMsg) || "用户不存在".equals(userMsg)) {
                        msg = new ResultMsg("F", "用户登录信息有误");
                    } else {
                        msg = new ResultMsg("F", userMsg);
                    }
                }
            } else {
                Token token = (Token) entity.getEntity();
                Cookie cookie = new Cookie(ToolsUtil.getInstance().getValueByKey("cookieName"),
                        token.getTokenId());
                cookie.setPath("/");
                cookie.setMaxAge(-1);
                Cookie ucsso = new Cookie("_uc.sso",
                        DesUtils.getInstance().decrypt(token.getUserEname()));
                ucsso.setPath("/");
                ucsso.setMaxAge(-1);
                response.addCookie(cookie);
                response.addCookie(ucsso);
                request.getSession().removeAttribute("loginUser");
                request.getSession().removeAttribute("tokenId");
                request.getSession().setAttribute("tokenId", token.getTokenId());
                log.info("[" + params.get("username") + "]登录成功！");
                //剔除loginInfo，解密email，userEname，mobile传明文
                JsonConfig jc = new JsonConfig();
                String config[] = { "loginInfo" };
                jc.setExcludes(config);
                String email = token.getEmail();
                String mobile = token.getMobile();
                String userEname = token.getUserEname();
                token.setEmail(DesUtils.getInstance().decrypt(email));
                token.setMobile(DesUtils.getInstance().decrypt(mobile));
                token.setUserEname(DesUtils.getInstance().decrypt(userEname));
                msg = new ResultMsg("T", JSONObject.fromObject(token, jc).toString());

                Map<String, Object> logMap = new HashMap<String, Object>();
                logMap.put("logOperationType", "login");
                logMap.put("logClassName", User.class.getName());
                logMap.put("logIp", maps.get("Client-IP"));
                logMap.put("log_userEname", token.getUserEname());
                log.info("登录成功日志："+logMap);
                LogClient.getInstance().execute(logMap);//添加日志
            }
        }
        return msg;
    }

    /**
     * description:  用户退出方法
     */
    private ResultMsg logout(HttpServletRequest request, HttpServletResponse response, Map params) {
        ResultMsg msg = new ResultMsg("F", "退出失败");
        String tokenCookie = PassportHelper.getInstance().getCurrCookie(request);
        String value = PassportHelper.getInstance().getCurrCookie(request, "_uc.sso");
        String userEname = DesUtils.getInstance().decrypt(value);
        if (null == params) {
            params = new HashMap();
        }
        params.put("tokenId", tokenCookie);
        params.put("userEname", userEname);
        String sysEname = ToolsUtil.getInstance().getValueByKey("sysEname");
        params.put("sysEname", sysEname);
        params.put("sysAccreditip", request.getRemoteAddr());
        ResultEntity entity = LoadRpcService.service()
                .doServiceClient("ssoService", "logout", params,
                        PortalPubFactory.getInstance().getRpcInfo("sso"));
        if (("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
            Map<String, Object> logMap = new HashMap<String, Object>();
            LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
            logMap.put("log_userEname", loginUser.getUserEname());

            clearLoginInfo(request, response);
            msg = new ResultMsg("T", "退出成功");

            logMap.put("logOperationType", "logout");
            logMap.put("logClassName", User.class.getName());
            logMap.put("logIp", PortalPubFactory.getLocalIp());
            LogClient.getInstance().execute(logMap);//添加日志
        }
        return msg;
    }

    private void clearLoginInfo(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        try {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = new Cookie(cookies[i].getName(), null);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        ArrayList lst = new ArrayList();
        Enumeration enumer = request.getSession().getAttributeNames();
        while (enumer.hasMoreElements()) {
            lst.add(enumer.nextElement());
        }
        for (int i = 0; i < lst.size(); i++) {
            request.getSession().removeAttribute(lst.get(i).toString());
        }
    }

    /**
     * description:  注册新用户
     */
    private ResultMsg regUser(HttpServletRequest request, HttpServletResponse response,
            Map<String, String> params) {
        ResultMsg msg = new ResultMsg("F", "注册失败");
        if (StrUtil.isNull(params.get("username"))) {
            msg = new ResultMsg("F", "用户名不能为空");
            return msg;
        }
        if (StrUtil.isNull(params.get("password"))) {//传过来的值需要加密
            msg = new ResultMsg("F", "密码不能为空");
            return msg;
        }
        if (StrUtil.isNull(params.get("password2"))) {
            msg = new ResultMsg("F", "密码不能为空");
            return msg;
        }
        if (!params.get("password").equals(params.get("password2"))) {//传过来的值需要加密
            msg = new ResultMsg("F", "两次密码不一致");
            return msg;
        }
        if (StrUtil.isNull(params.get("realname"))) {
            msg = new ResultMsg("F", "真实姓名不能为空");
            return msg;
        }
        try {
            ResultEntity entity = null;
            Map<String, Object> map = new HashMap<String, Object>();
            String realname = java.net.URLDecoder.decode(params.get("realname"), "UTF-8");
            map.put("userEname", params.get("username"));
            map.put("userPass", params.get("password"));
            map.put("userCname", realname);
            if (ToolsUtil.isNotNull(params.get("email"))) {
                map.put("email", params.get("email"));
            }
            if (ToolsUtil.isNotNull(params.get("mobile"))) {
                map.put("mobile", params.get("mobile"));
            }

            //判断是否发送邮件
            String isok = "注册成功";
            String mail_start = ToolsUtil.getInstance().getValueByKey("mail_start");
            //			if ("T".equals(mail_start) && ToolsUtil.isNotNull(params.get("email"))) {
            //				Map<String, String> paramsMail = new HashMap<String, String>();
            //				paramsMail.put("email", params.get("email"));
            //				paramsMail.put("userEname", map.get("userEname").toString());
            //				paramsMail.put("userCname", realname);
            //				log.info("邮件发送参数：" + paramsMail);
            //				boolean mark = sendMail(request, paramsMail);
            //				if (mark) {
            //					isok += ",已发送邮件！";
            //				} else {
            //					msg = new ResultMsg("F", "邮件发送失败！");
            //					return msg;
            //				}
            //			}
            String reqIp = RequestTools.getIp(request);
            map.put("Client-IP", reqIp);
            if (ToolsUtil.isNull(params.get("orgename"))) {//走单点登录
                String sysEname = ToolsUtil.getInstance().getValueByKey("sysEname");
                map.put("sysEname", sysEname);
                entity = LoadRpcService.service()
                        .doServiceClient("ssoService", "userOwRegService", map,
                                PortalPubFactory.getInstance().getRpcInfo("sso"));
            } else {//走UC
                String orgcname = params.get("orgcname");
                if (StrUtil.isNotEmpty(orgcname)) {
                    orgcname = java.net.URLDecoder.decode(orgcname, "UTF-8");
                }
                String sysEname = ToolsUtil.getInstance().getValueByKey("sys_ename");//系统名称
                map.put("sysEname", sysEname);
                if (ToolsUtil.isNotNull(params.get("usertype")))
                    map.put("userType", params.get("usertype"));
                if (ToolsUtil.isNotNull(params.get("phone")))
                    map.put("phone", params.get("phone"));
                map.put("orgEname", params.get("orgename"));
                if (ToolsUtil.isNotNull(params.get("orgcname")))
                    map.put("orgCname", orgcname);
                if (ToolsUtil.isNotNull(params.get("company")))
                    map.put("company", params.get("company"));
                if (ToolsUtil.isNotNull(params.get("usersex")))
                    map.put("userSex", params.get("usersex"));
                if (ToolsUtil.isNotNull(params.get("actFullEname")))
                    map.put("actFullEname", params.get("actFullEname"));
                if (!StrUtil.isNull(params.get("userstatus"))) {
                    map.put("userStatus", params.get("userstatus"));
                }
                if (!StrUtil.isNull(params.get("province"))) {
                    map.put("province", params.get("province"));
                }
                if (!StrUtil.isNull(params.get("city"))) {
                    map.put("city", params.get("city"));
                }
                entity = UctCoreClient.saveUserInfo(map);
            }
            if (("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
                String userId = String.valueOf(entity.getEntity());

                //记录授权会员角色日志
                Map<String, Object> actMap = new HashMap<String, Object>();
                actMap.put("userId", userId);
                actMap.put("userEname", params.get("username"));
                actMap.put("roleEname", "member");//前台注册的统一授权为会员角色
                entity = UctCoreClient.grantActToUser(actMap);
                log.error("网站注册时，统一授权为会员角色：" + JSONObject.fromObject(entity));

                //记录操作日志
                map.put("userId", userId);
                logInfo("save", reqIp, params.get("username"), map);
                msg = new ResultMsg("T", isok);
            } else {
                msg = new ResultMsg("F", StrUtil.doNull(entity.getMessage(), "注册失败"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
        }
        //		System.out.println(JSONObject.fromObject(msg));
        return msg;
    }

    private void logInfo(String logType, String logIp, String userEname, Map<String, Object> map) {
        Map<String, Object> logMap = new HashMap<String, Object>();
        logMap.put("logType", logType);
        logMap.put("logClassName", User.class.getName());
        logMap.put("logIp", logIp);
        logMap.put("log_userEname", userEname);
        logMap.putAll(map);
        LogClient.getInstance().execute(logMap);//添加日志
    }

    /**
     * description:  修改用户信息
     */
    private ResultMsg editUser(HttpServletRequest request, HttpServletResponse response,
            Map<String, String> params) {
        ResultMsg msg = new ResultMsg("F", "信息修改失败");
        String username = StrUtil.doNull(params.get("username"), "");
        String realname = StrUtil.doNull(params.get("realname"), "");
        String password = StrUtil.doNull(params.get("password"), "");////传过来的值需要加密
        String email = StrUtil.doNull(params.get("email"), "");
        String checkUserPass = StrUtil.doNull(params.get("checkUserPass"), "0");
        try {
            if ("1".equals(checkUserPass)) {
                String password2 = StrUtil.doNull(params.get("password2"), "");////传过来的值需要加密
                String oldpassword = StrUtil.doNull(params.get("oldpassword"), "");///传过来的值需要加密
                if (!password.equals(password2)) {
                    msg = new ResultMsg("F", "两次密码输入不一致");
                    return msg;
                }
                if (StrUtil.isNull(oldpassword)) {
                    msg = new ResultMsg("F", "旧密码不能为空");
                    return msg;
                }
                //oldpassword = MD5Utils.crypt(oldpassword);
                LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
                if (!oldpassword.equals(loginUser.getUserPass())) {
                    msg = new ResultMsg("F", "旧密码输入的不正确");
                    return msg;
                }
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("Client-IP",
                    StrUtil.doNull(params.get("Client-IP"), RequestTools.getIp(request)));
            if (StrUtil.isNotNull(params.get("userid"))) {
                map.put("userId", params.get("userid"));
            }
            if (StrUtil.isNotNull(username))
                map.put("userEname", username);
            if (StrUtil.isNotNull(realname))
                map.put("userCname", realname);
            if ("1".equals(checkUserPass)) {
                if (StrUtil.isNull(password)) {
                    msg = new ResultMsg("F", "密码不能为空");
                    return msg;
                }
                //password = MD5Utils.crypt(password);
                map.put("userPass", password);
            }
            if (StrUtil.isNotNull(email))
                map.put("email", email);
            if (StrUtil.isNotNull(params.get("phone")))
                map.put("phone", params.get("phone"));
            if (StrUtil.isNotNull(params.get("mobile")))
                map.put("mobile", params.get("mobile"));
            if (StrUtil.isNotNull(params.get("userRemark")))
                map.put("userRemark", params.get("userRemark"));
            ResultEntity entity = UctCoreClient.editUserInfo(map);
            if (("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
                logInfo("edit", request.getRemoteAddr(), username, map);
                msg = new ResultMsg("T", "信息修改成功");
                LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
                loginUser.setUserCname(realname);
                ResultEntity resultEntity = UctCoreClient.getUserByProperty("userEname", username);
                User u = (User) resultEntity.getEntity();
                loginUser.setUser(u);

                request.getSession().setAttribute("loginUser", loginUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return msg;
    }

    /**
     * description:  修改密码
     */
    private ResultMsg editUserPwd(HttpServletRequest request, HttpServletResponse response,
            Map<String, String> params) {
        ResultMsg msg = new ResultMsg("F", "密码修改失败");
        try {
            LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
            Map<String, Object> maps = new HashMap<String, Object>();
            maps.put("Client-IP",
                    StrUtil.doNull(params.get("Client-IP"), RequestTools.getIp(request)));
            if (null != loginUser) {
                maps.put("userEname", loginUser.getUserEname());
                maps.put("userId", loginUser.getUserId());
                maps.put("userPass", params.get("userPass"));////传过来的值需要加密
            } else {
                ResultEntity entity = UctCoreClient
                        .getUserByProperty("userEname", params.get("username"));
                if (("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
                    User user = (User) entity.getEntity();
                    maps.put("userEname", user.getUserEname());
                    maps.put("userId", user.getUserId());
                    maps.put("userPass", user.getUserPass());
                } else {
                    msg = new ResultMsg("F", "修改失败：" + entity.getMessage());
                    return msg;
                }
            }
            String sysEname = ToolsUtil.getInstance().getValueByKey("sysEname");
            maps.put("newPass", params.get("newPass"));//传过来的值需要加密
            maps.put("sysEname", sysEname);
            ResultEntity entity = LoadRpcService.service()
                    .doServiceClient("ssoService", "updatePwd", maps,
                            PortalPubFactory.getInstance().getRpcInfo("sso"));
            if (("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
                msg = new ResultMsg(String.valueOf(entity.getEntity()), entity.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return msg;
    }

    /**
     * description:  找回密码
     */
    private ResultMsg findPwd(HttpServletRequest request, HttpServletResponse response,
            Map<String, String> params) {
        ResultMsg msg = new ResultMsg("F", "密码找回失败");
        String mail_start = ToolsUtil.getInstance().getValueByKey("mail_start");
        if (!"T".equals(mail_start)) {
            msg = new ResultMsg("F", "服务端已停用发送邮件通知业务");
            return msg;
        }
        ResultEntity entity = UctCoreClient.getUserByProperty("userEname", params.get("username"));
        if (("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
            User user = (User) entity.getEntity();
            String userEmail = user.getEmail();
            if (StrUtil.isNotNull(userEmail)) {
                params.put("email", userEmail);
                params.put("userEname", user.getUserEname());
                params.put("userCname", user.getUserCname());
                boolean mark = sendMail(request, params);
                if (mark) {
                    msg = new ResultMsg("T", "请登录邮箱查收您的邮件！");
                } else {
                    msg = new ResultMsg("F", "给账户[" + userEmail + "]发送邮件失败！");
                }
            } else {
                msg = new ResultMsg("F", "此帐号还未绑定邮箱");
            }
        } else {
            msg = new ResultMsg("F", "此帐号不存在");
        }
        return msg;
    }

    /**
     * description:  发送密码找回邮件
     */
    private boolean sendMail(HttpServletRequest request, Map<String, String> map) {
        String email1 = TeaUtil
                .encryptByTea(map.get("email"));//DesUtils.getInstance().encrypt(map.get("email"));
        String userEname = TeaUtil.encryptByTea(
                map.get("userEname"));//DesUtils.getInstance().encrypt(map.get("userEname"));
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request
                .getServerPort() + request.getContextPath();

        String link = basePath + "/res/uct/checkEmail?doCode=U0006&u=" + userEname + "&e=" + email1
                + "&rand=" + System.currentTimeMillis();
        Map<String, String> params = new HashMap<String, String>();
        params.put("userEmail", map.get("email"));
        params.put("content", link);
        params.put("userCname", map.get("userCname"));
        String emailTitle = request.getParameter("emailTitle");
        emailTitle = StrUtil.isNotNull(emailTitle) ? emailTitle : map.get("userEname");
        params.put("title", emailTitle + "-会员找回密码");
        params.put("tempName", "mailTemplate.inc");//指定使用的模板
        params.put("emailPwd", ToolsUtil.getInstance().getValueByKey("mail_pwd"));
        params.put("host", ToolsUtil.getInstance().getValueByKey("mail_host"));
        params.put("from", ToolsUtil.getInstance().getValueByKey("mail_user"));
        params.put("protocol", ToolsUtil.getInstance().getValueByKey("mail.protocol"));
        params.put("platformName", ToolsUtil.getInstance().getValueByKey("mail.platform.name"));
        //发送邮件
        SendService service = (SendService) BeanFactory.getInstance().getBeans("sendEmail");
        boolean mark = service.sendMessage(params);
        log.info("给【" + map.get("email") + "】发送邮件的结果：" + mark);
        return mark;
    }

    //用户注册账号唯一判断
    private Object isExist(HttpServletRequest request, Map<String, String> params) {
        String username = StrUtil.doNull(params.get("uctUser.userEname"), "");
        ResultEntity entity = null;
        entity = UctCoreClient.getUserByProperty("userEname", username);
        return entity;
    }

}
